<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\Exception;
use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->where(['delete_time'=>0])
            ->field('id,code,nickname,mobile,is_active,level_id');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')->where(['delete_time'=>0])
            ->field('id,code,photo,nickname,mobile,team_total,level_id,newly_total_1,newly_total_2,team_total_1,team_total_2,place_code,position')->with('level');
//        newly_total_1+team_total_1 as newly_team_total_1,newly_total_2+team_total_2 as newly_team_total_2
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid'      => $parentId,
                'code'     => $parentCode,
                'algebra'  => 1,
                'new_uid'  => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,' . $new_code . ' as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($num,$order_type, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($num))->update();
            $team_total = 'team_total_'.$order_type;
            User::whereIn('id', $all_id)->inc($team_total, floatval($num))->update();
        }

    }

    //销售提成
    public static function sales_commission($p_uid,$uid)
    {
        $sales_commission = Cache::get('system')['sales_commission'];
        Target::Account()->basics($p_uid, 'reward', $sales_commission, '销售提成', '+')
            ->createBonus($uid, 1);
        if ($sales_commission > 0) {
            Event::trigger('Statistics', ['key' => 'expend', 'value' => $sales_commission]);
        }
    }

    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus($uid, $total, $recoil_count): array
    {
        try {

            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $poor = 0;
            $level_id = 0;
            $expendTotal = 0;
            $flat = 0;
            $flat_open = true;
            $recoil_tp = Cache::get('system')['recoil_tp'];
            //$flat_total = 0;
            foreach ($list as $item) {
                if ($item->user->is_active != 2 || $item->user->is_out) continue;
                //大区加速
                if ($item->user->recoil_count <= 1 && $recoil_count <= 1) {
                    //大区加速
                    $areaAll = User::where('parent_id', $item->uid)->order('team_total', 'desc')
                        ->column('my_total+team_total as team_total,id');
                    $max_speed = Cache::get('system')['max_speed'];
                    if (!empty($areaAll) && $max_speed > 0 && count($areaAll) > 1) {
                        $max = array_shift($areaAll);
                        $ids = Relation::where(['uid' => $max['id']])->column('new_uid');
                        $ids[] = $max['id'];
                        if (in_array($uid, $ids)) {
                            $amount = UserRelease::testingCapping($item->uid, round($total * $max_speed, 2));
                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '大市场加速', '+')
                                ->createBonus($uid, 5);
                        }
                    }
                }
                //直推
                if ($item->algebra == 1) {
                    $count = User::where(['is_active' => 2, 'parent_id' => $item->uid])->count();
                    $tp = $count >= 3 ? Cache::get('system')['speed_3'] : Cache::get('system')['speed_' . $count];
                    $amount = UserRelease::testingCapping($item->uid, round($total * $tp, 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;
                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '消费分润', '+')
                            ->createBonus($uid, 2);
                    }
                }
                //团队奖
                $level = Level::where('id', $item->user->level_id)->find();
                if (empty($level)) continue;
                if ($item->user->level_id > $level_id && $level->tp > $poor) {
                    $amount = UserRelease::testingCapping($item->uid, round($total * ($level->tp - $poor), 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;

                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '培育分润', '+')
                            ->createBonus($uid, 3);
                    }
                    $poor = $level->tp;
                    $level_id = $item->user->level_id;
                    $flat = $item->user->level_id;
                    $flat_open = true;
                    //$flat_total = $amount;
                } else {

                    if ($item->user->level_id == $flat && $flat_open) {
                        $amount = UserRelease::testingCapping($item->uid, round($total * $level->flat_tp, 2));
                        if ($amount > 0) {

                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '平级奖', '+')
                                ->createBonus($uid, 4);

                            $expendTotal += $amount;
                        }
                        $flat_open = false;
                    }
                }
            }
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $min_total = User::geMinTeam($item->user->id);
                $level = Level::where('id', '>', $item->user->level_id)
                    ->where('min_team', '<=', $min_total)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
